const fs = require('fs').promises;
const { readPackageJson, clear, execListen, logBright, updateElectronPkg, updateElectronTsPkg } = require('./utils/index');

async function main() {
  clear()

  const json = await readPackageJson(0)
  if (!json) {
    console.log("获取配置文件失败")
    return
  }

  const pomJson = await readPackageJson(1)
  if (!pomJson) {
    console.log("获取构建配置文件失败")
    return
  }

  let electronJson = await readPackageJson(3)
  if (electronJson) {
    await updateElectronPkg(electronJson, pomJson?.build?.dist, pomJson?.build?.output)
  } else {
    console.log("获取electron配置文件失败")
    return
  }

  let electronTsJson = await readPackageJson(2)
  if (electronTsJson) {
    await updateElectronTsPkg(electronTsJson, pomJson?.build?.dist)
  } else {
    console.log("获取tsconfig.electron配置文件失败")
    return
  }

  let startTime = new Date()
  logBright('移除旧文件');
  try {
    await fs.rm(pomJson?.build?.dist, { recursive: true })
  } catch (error) { }
  try {
    await fs.rm(pomJson?.build?.output, { recursive: true })
  } catch (error) { }


  console.log(`---耗时${(new Date() - startTime) / 1000}秒`)
  startTime = new Date()

  logBright('正在编译electron代码');
  await execListen(["tsc", "--project", "tsconfig.electron.json"])
  console.log(`---耗时${(new Date() - startTime) / 1000}秒`)
  startTime = new Date()

  logBright('正在打包vue项目');
  await execListen(["yarn", "workspace", `@${json.name}/web`, "vite build"]);
  startTime = new Date()

  logBright('正在打包electron项目');
  await execListen(["yarn", "workspace", `@${json.name}/electron`, "electron-builder", "--x64"]);
}

main()